﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Core.TransactionsResponse;

namespace MS.InformationManagement.BLL.UserProfileManagement
{
    public class CreateUserProfileCommand : ICommandWithResponse
    {
        #region private methods

        string _profileName;
        List<Roles> _roleCollection;
        bool _isSiteContributor;
        List<int> _itemsId = new List<int>();

        #endregion

        #region constructors

        public CreateUserProfileCommand(string profileName, List<Roles> roleCollection, bool isSiteContributor)
        {
            _profileName = profileName;
            _roleCollection = roleCollection;
            _isSiteContributor = isSiteContributor;
        }

        #endregion

        #region Implemented Methods

        public ITransactionResponse Execute()
        {
            CreateUserProfileCommandResponse response = new CreateUserProfileCommandResponse();
            VincularPerfiles newElement = null;

            using (DCDocumentCenterDataContext ctx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var entity = (from item in ctx.Perfiles
                              where item.Perfil == _profileName
                              select item).FirstOrDefault();

                if (entity != null)
                    throw new Exception(string.Format("El perfil con nombre {0} ya existe en la lista de perfiles", _profileName));

                newElement = new VincularPerfiles { Title = string.Empty, Perfil = _profileName, ContribuyenteEnSitio = _isSiteContributor };
                foreach (Roles currentRole in _roleCollection)
                {
                    ctx.Roles.Attach(currentRole);
                    newElement.TipoRole.Add(currentRole);
                }
                ctx.Perfiles.InsertOnSubmit(newElement);
                ctx.SubmitChanges();

                response.CurrentPerfil = newElement;
                response.ResponseMessage = "Exito";
                response.Result = true;

                _itemsId.Add(newElement.Id.Value);
            }

            return response;
        }

        public void Undo()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foreach (int id in _itemsId)
                {
                    var entity = (from item in dc.Perfiles
                                  where item.Id == id
                                  select item).FirstOrDefault();

                    dc.Perfiles.DeleteOnSubmit(entity);
                    dc.SubmitChanges();
                }
            }
        }

        #endregion
    }
}
